package RequestLimit

import (
	"net/http"
	"sync"
	"time"
)

type RequestLimitService struct {
	Interval time.Duration
	MaxCount map[string]int
	Lock     sync.Mutex
	ReqCount map[string]int
}

func IpGet(r *http.Request) string {
	ips := r.Header.Get("X-Forwarded-For")
	//ips := r.Header.Get("X-Forwarded-For")
	//ips := strings.Split(r, ":")[0]
	//if strings.Contains(ips, "[") && strings.Contains(ips, "]") {
	//	ips = strings.Split(ips, "[")[1]
	//	ips = strings.Split(ips, "]")[0]
	//}
	ip = ips
	return ips
}

func NewRequestLimitService(interval time.Duration, ips string, maxCnt int) *RequestLimitService {
	var MaxCount = make(map[string]int)
	MaxCount[ips] = maxCnt
	reqLimit := &RequestLimitService{
		Interval: interval,
		MaxCount: MaxCount,
	}

	go func() {
		ticker := time.NewTicker(interval)
		for {
			<-ticker.C
			reqLimit.Lock.Lock()
			reqLimit.ReqCount = make(map[string]int)
			reqLimit.Lock.Unlock()
		}
	}()

	return reqLimit
}

func (reqLimit *RequestLimitService) Increase(ips string) {
	reqLimit.Lock.Lock()
	defer reqLimit.Lock.Unlock()
	if reqLimit.ReqCount == nil {
		reqLimit.ReqCount = make(map[string]int)
	}
	reqLimit.ReqCount[ips] += 1
}

func (reqLimit *RequestLimitService) IsAvailable(ips string) bool {
	reqLimit.Lock.Lock()
	defer reqLimit.Lock.Unlock()
	return reqLimit.ReqCount[ips] < limit
}

var limit = 10 // 访问量
var Second time.Duration = 3
var RequestLimit = NewRequestLimitService(Second*time.Second, ip, limit)
var ip string

//func helloHandler(w http.ResponseWriter, r *http.Request) {
//	if RequestLimit.IsAvailable() {
//		RequestLimit.Increase()
//		fmt.Println(RequestLimit.ReqCount)
//		io.WriteString(w, "Hello world!\n")
//	} else {
//		fmt.Println("Reach request limiting!")
//		io.WriteString(w, "Reach request limit!\n")
//	}
//}

//func main() {
//	fmt.Println("Server Started!")
//	http.HandleFunc("/", helloHandler)
//	http.ListenAndServe(":8000", nil)
//}
